<template>
  <div class="new-record-page">
    <van-nav-bar
      title="新记账"
      left-arrow
      @click-left="router.back()"
    />
    
    <!-- 步骤导航 -->
    <div class="steps">
      <div class="step-item" :class="{ active: currentStep === 'selectCustomer' }" @click="currentStep = 'selectCustomer'">
        选人
      </div>
      <div class="step-item" :class="{ active: currentStep === 'selectProducts' }" @click="goToProductSelection">
        选货
      </div>
      <div class="step-item" :class="{ active: currentStep === 'adjustPrice' }" @click="goToPriceAdjustment">
        改价
      </div>
    </div>

    <!-- 客户选择部分 -->
    <div class="customer-selection" v-if="currentStep === 'selectCustomer'">
      <div class="search-bar">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索客户"
          shape="round"
        />
      </div>

      <div class="customer-list">
        <van-cell 
          v-for="customer in filteredCustomers" 
          :key="customer.id"
          :title="customer.name"
          :label="customer.phone"
          @click="selectCustomer(customer)"
        />

        <div class="add-customer">
          <van-button 
            icon="plus" 
            plain 
            block 
            type="primary" 
            @click="addNewCustomer"
          >
            新增客户
          </van-button>
        </div>
      </div>
    </div>

    <!-- 商品选择部分 -->
    <div class="product-selection" v-else-if="currentStep === 'selectProducts'">
      <div class="content">
        <!-- 左侧分类栏 -->
        <div class="category-sidebar">
          <div
            v-for="(category, index) in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: activeCategory === index }"
            @click="switchCategory(index)"
            :ref="el => { if(el) categoryRefs[index] = el as HTMLElement }"
          >
            {{ category.name }}
          </div>
        </div>

        <!-- 右侧商品列表 -->
        <div class="product-content" ref="productContent" @scroll="handleProductScroll">
          <!-- 当前分类标题 -->
          <div class="category-title">
            <div class="title-text">{{ categories[activeCategory]?.name || '商品列表' }}</div>
            <div class="product-count">{{ filteredProducts.length }}个商品</div>
          </div>

          <!-- 商品列表 -->
          <div class="product-list">
            <div v-for="product in filteredProducts" :key="product.id" class="product-item">
              <div class="product-card">
                <img :src="product.image" alt="商品图片" class="product-image" />
                <div class="product-info">
                  <div class="product-name">{{ product.name }}</div>
                  <div class="product-desc">{{ product.description }}</div>
                  <div class="product-price-action">
                    <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
                    <div class="quantity-control">
                      <van-button
                        plain
                        size="mini"
                        icon="minus"
                        class="quantity-btn"
                        @click="decreaseQuantity(product)"
                        :disabled="!getCartItemQuantity(product.id)"
                      />
                      <span class="quantity">{{ getCartItemQuantity(product.id) }}</span>
                      <van-button
                        plain
                        size="mini"
                        icon="plus"
                        class="quantity-btn"
                        @click="addToCart(product)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="filteredProducts.length === 0" class="empty-state">
              <van-empty description="暂无商品" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 价格调整部分 -->
    <div class="price-adjustment" v-else-if="currentStep === 'adjustPrice'">
      <div class="order-items">
        <van-cell-group title="已选商品">
          <van-cell 
            v-for="item in cartItems" 
            :key="item.id"
            :title="item.name"
          >
            <template #label>
              <div class="order-item-detail">
                <div class="order-item-quantity">x{{ item.quantity }}</div>
                <div class="order-item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>

        <van-field
          v-model="discountAmount"
          type="digit"
          label="优惠金额"
          placeholder="请输入优惠金额"
        />

        <van-cell title="订单金额">
          <span class="order-total">¥{{ orderTotal.toFixed(2) }}</span>
        </van-cell>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <template v-if="currentStep === 'selectCustomer'">
        <van-button 
          round 
          block 
          type="primary" 
          :disabled="!selectedCustomer"
          @click="goToProductSelection"
        >
          下一步
        </van-button>
      </template>

      <template v-else-if="currentStep === 'selectProducts'">
        <div class="cart-bar" v-if="cartItems.length > 0">
          <div class="cart-info">
            <div class="cart-total">
              <span class="total-label">合计：</span>
              <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="cart-count">共{{ totalCount }}件商品</div>
          </div>
          <van-button round type="primary" class="next-button" @click="goToPriceAdjustment">
            下一步
          </van-button>
        </div>
        <van-button
          v-else
          round
          block
          type="primary"
          disabled
        >
          请选择商品
        </van-button>
      </template>

      <template v-else-if="currentStep === 'adjustPrice'">
        <van-button 
          round 
          block 
          type="primary" 
          @click="submitOrder"
        >
          保存订单
        </van-button>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// 步骤控制
const currentStep = ref('selectCustomer')

// 客户相关
const searchKeyword = ref('')
const selectedCustomer = ref<Customer | null>(null)

// 客户数据类型
interface Customer {
  id: number;
  name: string;
  phone: string;
}

// 模拟客户数据
const customers = ref<Customer[]>([
  { id: 1, name: '张三', phone: '13800138000' },
  { id: 2, name: '李四', phone: '13900139000' },
  { id: 3, name: '王五', phone: '13700137000' }
])

// 筛选客户
const filteredCustomers = computed(() => {
  if (!searchKeyword.value) return customers.value
  const keyword = searchKeyword.value.toLowerCase()
  return customers.value.filter(
    customer => 
      customer.name.toLowerCase().includes(keyword) || 
      customer.phone.includes(keyword)
  )
})

// 选择客户
const selectCustomer = (customer: Customer) => {
  selectedCustomer.value = customer
  showToast(`已选择客户: ${customer.name}`)
}

// 新增客户
const addNewCustomer = () => {
  router.push('/customer/add')
}

// 分类数据
interface Category {
  id: number;
  name: string;
}

// 商品数据
interface Product {
  id: number;
  name: string;
  price: number;
  image: string;
  description: string;
  categoryId: number;
}

// 购物车商品
interface CartItem {
  id: number;
  productId: number;
  name: string;
  price: number;
  quantity: number;
  image: string;
}

// 模拟分类数据
const categories = ref<Category[]>([
  { id: 1, name: '饮料' },
  { id: 2, name: '零食' },
  { id: 3, name: '日用品' },
  { id: 4, name: '当季新品' },
  { id: 5, name: '今日特价' },
  { id: 6, name: '联名套餐' }
])

// 模拟商品数据
const allProducts = ref<Product[]>([
  {
    id: 1,
    name: '鲜萃咖啡',
    price: 13.9,
    image: '/products/coffee1.png',
    description: '鲜萃现泡 0植脂末',
    categoryId: 1
  },
  {
    id: 2,
    name: '生椰拿铁',
    price: 13.9,
    image: '/products/coffee2.png',
    description: '4年突破12亿杯 原创YYDS!',
    categoryId: 1
  },
  {
    id: 3,
    name: '橙C美式',
    price: 13.9,
    image: '/products/coffee3.png',
    description: '0脂 | 一杯橙汁含量≈1个橙子',
    categoryId: 1
  },
  {
    id: 4,
    name: '轻咖柠檬茶',
    price: 13.9,
    image: '/products/tea1.png',
    description: '0脂|广东香水柠檬|含生豆精华',
    categoryId: 4
  },
  {
    id: 5,
    name: '爆浆曲奇',
    price: 8.0,
    image: '/products/snack1.png',
    description: '香脆可口 浓郁奶香',
    categoryId: 2
  },
  {
    id: 6,
    name: '软欧包',
    price: 9.5,
    image: '/products/snack2.png',
    description: '松软可口 早餐必备',
    categoryId: 2
  }
])

// 当前激活的分类索引
const activeCategory = ref(0)

// 购物车商品
const cartItems = ref<CartItem[]>([])

// 价格调整相关
const discountAmount = ref('')

// 根据当前分类筛选商品
const filteredProducts = computed(() => {
  const categoryId = categories.value[activeCategory.value]?.id
  if (!categoryId) return []
  return allProducts.value.filter(p => p.categoryId === categoryId)
})

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 计算购物车商品总数
const totalCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算订单总价（含折扣）
const orderTotal = computed(() => {
  const discount = parseFloat(discountAmount.value) || 0
  return Math.max(0, totalPrice.value - discount)
})

// 切换分类
const switchCategory = (index: number) => {
  activeCategory.value = index
  scrollToCategory(index)
}

// 获取购物车中商品数量
const getCartItemQuantity = (productId: number): number => {
  const item = cartItems.value.find(item => item.productId === productId)
  return item ? item.quantity : 0
}

// 添加商品到购物车
const addToCart = (product: Product) => {
  const existingItem = cartItems.value.find(item => item.productId === product.id)
  
  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.value.push({
      id: Date.now(),
      productId: product.id,
      name: product.name,
      price: product.price,
      quantity: 1,
      image: product.image
    })
  }
}

// 减少购物车中商品数量
const decreaseQuantity = (product: Product) => {
  const index = cartItems.value.findIndex(item => item.productId === product.id)
  if (index === -1) return
  
  const item = cartItems.value[index]
  if (item.quantity > 1) {
    item.quantity -= 1
    showToast({
      type: 'success',
      message: `已减少${product.name}`,
      position: 'bottom'
    })
  } else {
    cartItems.value.splice(index, 1)
    showToast({
      type: 'success',
      message: `已移除${product.name}`,
      position: 'bottom'
    })
  }
}

// 步骤导航
const goToProductSelection = () => {
  if (!selectedCustomer.value && currentStep.value === 'selectCustomer') {
    showToast('请先选择客户')
    return
  }
  currentStep.value = 'selectProducts'
}

const goToPriceAdjustment = () => {
  if (cartItems.value.length === 0) {
    showToast('请先选择商品')
    return
  }
  currentStep.value = 'adjustPrice'
}

// 提交订单
const submitOrder = () => {
  if (!selectedCustomer.value) {
    showToast('请选择客户')
    return
  }
  
  if (cartItems.value.length === 0) {
    showToast('请选择商品')
    return
  }
  
  // 创建订单对象
  const order = {
    customerId: selectedCustomer.value.id,
    customerName: selectedCustomer.value.name,
    items: cartItems.value,
    totalPrice: totalPrice.value,
    discount: parseFloat(discountAmount.value) || 0,
    finalPrice: orderTotal.value,
    createdAt: new Date().toISOString()
  }
  
  console.log('创建订单:', order)
  
  showToast({
    type: 'success',
    message: '订单创建成功'
  })
  
  // 跳转回首页
  router.push('/')
}

// 分类自动切换相关
const productContent = ref<HTMLElement | null>(null)
const categoryRefs: HTMLElement[] = []
let scrolling = false

// 处理右侧商品列表滚动事件
const handleProductScroll = () => {
  if (scrolling || !productContent.value) return
  
  const scrollTop = productContent.value.scrollTop
  // 使用计时器节流，优化滚动性能
  scrolling = true
  setTimeout(() => {
    scrolling = false
    
    // 根据滚动位置确定当前应该激活的分类
    // 简单实现：根据滚动位置比例确定分类索引
    const maxScroll = productContent.value!.scrollHeight - productContent.value!.clientHeight
    const scrollRatio = scrollTop / maxScroll
    const newIndex = Math.min(
      Math.floor(scrollRatio * categories.value.length),
      categories.value.length - 1
    )
    
    if (newIndex !== activeCategory.value) {
      activeCategory.value = newIndex
      scrollCategoryIntoView(newIndex)
    }
  }, 200)
}

// 滚动到特定分类的商品区域
const scrollToCategory = (index: number) => {
  if (!productContent.value) return
  
  scrolling = true
  const maxScroll = productContent.value.scrollHeight - productContent.value.clientHeight
  const targetRatio = index / (categories.value.length - 1)
  const targetScrollTop = maxScroll * targetRatio
  
  productContent.value.scrollTop = targetScrollTop
  
  setTimeout(() => {
    scrolling = false
  }, 300)
}

// 确保左侧分类栏中的活动分类是可见的
const scrollCategoryIntoView = (index: number) => {
  const categoryItem = categoryRefs[index]
  if (categoryItem) {
    categoryItem.scrollIntoView({
      behavior: 'smooth',
      block: 'nearest'
    })
  }
}

onMounted(() => {
  console.log('新记账页面初始化')
})

// 监听当前激活分类变化
watch(activeCategory, (newIndex) => {
  scrollCategoryIntoView(newIndex)
})
</script>

<style lang="scss" scoped>
.new-record-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.steps {
  display: flex;
  background: #fff;
  padding: 12px 0;
  margin-bottom: 12px;
  
  .step-item {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #969799;
    position: relative;
    
    &.active {
      color: #1989fa;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -12px;
        left: 50%;
        transform: translateX(-50%);
        width: 24px;
        height: 3px;
        background: #1989fa;
        border-radius: 2px;
      }
    }
  }
}

.customer-selection {
  flex: 1;
  
  .search-bar {
    padding: 0 12px;
  }
  
  .customer-list {
    padding: 12px;
    
    .add-customer {
      margin-top: 20px;
    }
  }
}

.product-selection {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .content {
    display: flex;
    flex: 1;
    overflow: hidden;
    height: calc(100vh - 46px - 60px - 44px); // 减去导航栏、底部购物车栏和步骤导航的高度
  }
}

.category-sidebar {
  width: 90px;
  background: #f5f5f5;
  overflow-y: auto;
  
  .category-item {
    padding: 16px 12px;
    text-align: center;
    font-size: 14px;
    color: #323233;
    position: relative;
    
    &.active {
      background: #fff;
      color: #1989fa;
      font-weight: 500;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background: #1989fa;
      }
    }
  }
}

.product-content {
  flex: 1;
  overflow-y: auto;
  background: #fff;
  
  .category-title {
    padding: 12px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f5f5;
    
    .title-text {
      font-size: 16px;
      font-weight: 500;
    }
    
    .product-count {
      font-size: 12px;
      color: #969799;
    }
  }
  
  .product-list {
    padding: 12px;
    
    .product-item {
      margin-bottom: 12px;
    }
    
    .product-card {
      display: flex;
      align-items: center;
      padding: 12px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }
    
    .product-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 12px;
    }
    
    .product-info {
      flex: 1;
    }
    
    .product-name {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 4px;
    }
    
    .product-desc {
      font-size: 12px;
      color: #969799;
      margin-bottom: 8px;
    }
    
    .product-price-action {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .product-price {
      color: #ee0a24;
      font-size: 16px;
      font-weight: 500;
    }
    
    .quantity-control {
      display: flex;
      align-items: center;
      
      .quantity {
        width: 28px;
        text-align: center;
      }
      
      .quantity-btn {
        padding: 0;
        width: 24px;
        height: 24px;
      }
    }
  }
  
  .empty-state {
    padding: 40px 0;
  }
}

.price-adjustment {
  flex: 1;
  padding: 12px;
  
  .order-items {
    background: #fff;
    border-radius: 8px;
    
    .order-item-detail {
      display: flex;
      justify-content: space-between;
    }
    
    .order-total {
      color: #ee0a24;
      font-size: 18px;
      font-weight: 500;
    }
  }
}

.bottom-bar {
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cart-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .cart-info {
    .cart-total {
      .total-label {
        font-size: 14px;
      }
      
      .total-price {
        font-size: 18px;
        font-weight: 500;
        color: #ee0a24;
      }
    }
    
    .cart-count {
      font-size: 12px;
      color: #969799;
    }
  }
  
  .next-button {
    height: 36px;
    min-width: 100px;
  }
}
</style> 